import React, {Component} from 'react';
import {FlatList, Image, StatusBar, StyleSheet, Text, ToastAndroid, TouchableNativeFeedback, View} from 'react-native';
import * as Color from "../../../lib.xjs/constant/Color";
import * as BizConstant from "../../constant/BizContant";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import {UUID} from "../../../lib.xjs/util/UUID";
import BizUser from "../../entity/BizUser";

const ic_avatar_default = require('../../../../img/gaqu/ic_gaqu_cabin.png');
const ITEM_HEIGHT = 100;

/** 仓体列表 */
export default class CabinReportList extends Component {

    _mFlatList;

    static navigationOptions = ({navigation}) => ({
        title: '仓体昨日报表',
    });

    constructor(props) {
        super(props);
        this.state = {
            /** 是否正在刷新 */
            mIsRefresh: false,
            /** 数据源 */
            mDatas: [],
        };
    }

    componentDidMount(): void {
        this._getDatas(new Date(), false);
    }

    render() {
        return (
            <View style={{flex: 1, backgroundColor: Color.windowWhite}}>
                <StatusBar
                    hidden={false}
                    translucent={false}
                    backgroundColor={Color.colorPrimaryDark}/>
                <FlatList
                    ref={(flatList) => this._mFlatList = flatList}

                    data={this.state.mDatas}
                    renderItem={(item) => this._renderItem(item)}
                    keyExtractor={(item, index) => ("index" + index + item)}

                    refreshing={this.state.mIsRefresh}
                    onRefresh={this._onRefresh}

                    getItemLayout={this.getItemLayout}
                />
                <HttpHelper ref={'http'}/>
            </View>
        );
    }

    /**
     * 可选优化项。但是实际测试中，如果不做该项优化，性能会差很多。
     * 所以强烈建议做此项优化！如果不做该项优化，每个列表都需要事先渲染一次，动态地取得其渲染尺寸，然后再真正地渲染到页面中。
     * 如果预先知道列表中的每一项的高度(ITEM_HEIGHT)和其在父组件中的偏移量(offset)和位置(index)，就能减少一次渲染。
     * 这是很关键的性能优化点
     * @param data
     * @param index
     * @returns {{length: number, offset: number, index: *}}
     */
    getItemLayout = (data, index) => {
        return {length: ITEM_HEIGHT, offset: (ITEM_HEIGHT + 2) * index, index}
    };

    /**
     * 将列表元素和数据结合在一起，生成列表。
     * @param item 是data属性中的每个列表的数据（ Array<object> 中的 object) 。
     */
    _renderItem = (item) => {
        return <View style={styles.item_layout_touch_bg}>
            <TouchableNativeFeedback onPress={() => this._onClickItem(item)}>
                <View style={styles.item_layout}>
                    <View style={styles.item_ing_line1}>
                        <Image style={styles.item_head}
                               source={ic_avatar_default}
                               resizeMode={Image.resizeMode.center}/>
                        <Text style={{fontSize: 18}}>{item.item.cangName}</Text>
                    </View>

                    <View style={{height: '90%', width: 0.5, backgroundColor: Color.lightGray, marginHorizontal: 10,}}/>

                    <View
                        style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start'}}>
                        <View style={{
                            width: '100%',
                            flexDirection: 'row',
                            justifyContent: 'space-between',
                            alignItems: 'center'
                        }}>

                            <View style={{flex: 1, justifyContent: 'flex-start'}}>
                                <Text style={{fontSize: 36, color: Color.colorPrimaryLight}}>
                                    {item.item.allUserNum}
                                    <Text style={{fontSize: 16}}>注</Text>
                                </Text>
                            </View>

                            <View style={{flex: 1, justifyContent: 'flex-start'}}>
                                <Text style={{fontSize: 40, color: Color.orange}}>
                                    {item.item.allCertifiedUserNum}
                                    <Text style={{fontSize: 16}}>认</Text>
                                </Text>
                            </View>

                            <View style={{flex: 1, justifyContent: 'flex-start'}}>
                                <Text style={{fontSize: 40, color: Color.greenLight}}>
                                    {item.item.allPayedUserNum}
                                    <Text style={{fontSize: 16}}>押</Text>
                                </Text>
                            </View>
                        </View>

                        <View style={{
                            width: '100%',
                            flexDirection: 'row',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                        }}>
                            <View style={{flex: 2, justifyContent: 'flex-start'}}>
                                <Text style={styles.text_tag}>
                                    运动
                                </Text>
                            </View>

                            <View style={{flex: 3, justifyContent: 'flex-start'}}>
                                <Text style={{fontSize: 14}}>
                                    共
                                    <Text style={{fontSize: 20}}>{item.item.activeUserNum}</Text>
                                    <Text style={{fontSize: 14}}>人</Text>
                                </Text>
                            </View>

                            <View style={{flex: 3, justifyContent: 'flex-start'}}>
                                <Text style={{fontSize: 14}}>
                                    收
                                    <Text style={{fontSize: 20}}>{item.item.totalConsumeMoney}</Text>
                                    <Text style={{fontSize: 14}}>元</Text>
                                </Text>
                            </View>
                        </View>

                        <View style={{
                            width: '100%',
                            flexDirection: 'row',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                        }}>
                            <View style={{flex: 2, justifyContent: 'flex-start'}}>
                                <Text style={styles.text_tag}>
                                    押金
                                </Text>
                            </View>

                            <View style={{flex: 3, justifyContent: 'flex-start'}}>
                                <Text style={{fontSize: 14}}>
                                    交
                                    <Text style={{fontSize: 20}}>{item.item.timeDepositer}</Text>
                                    <Text style={{fontSize: 14}}>次</Text>
                                </Text>
                            </View>

                            <View style={{flex: 3, justifyContent: 'flex-start'}}>
                                <Text style={{fontSize: 14}}>
                                    退
                                    <Text style={{fontSize: 20}}>{item.item.timeRefunder}</Text>
                                    <Text style={{fontSize: 14}}>次</Text>
                                </Text>
                            </View>
                        </View>
                    </View>
                </View>
            </TouchableNativeFeedback>
        </View>


    };

    /** 获取数据 */
    _getDatas(lastTime: Date, isClear: boolean): void {
        if (!this.refs.http) return;
        // let head = new Map();
        // head.set("token", "36b4b4dc1e77e51f28b44fa712847a01");

        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("searchStartTime", new Date().DateAdd('d', -1).Format("yyyy-MM-dd hh:mm:ss"));
        body.set("searchEndTime", new Date().Format("yyyy-MM-dd hh:mm:ss"));
        body.set("page", "1");
        body.set("limit", "10000");

        this.refs.http.setURL(BizConstant.GET_CABIN_REPORT)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                if (!res.page.list) return;

                // 初始化全局变量
                let datas = res.page.list;
                if (!isClear) datas = [...this.state.mDatas, ...datas];

                this.setState({
                    mDatas: datas,
                });
            })
            .setTimeout(10 * 1000)
            .start(false);
    }

    /** 下拉时促发 */
    _onRefresh = () => {
        if (this.state.mIsRefresh) return;
        ToastAndroid.show('正在刷新中.... ', ToastAndroid.SHORT);
        this.setState({
            mIsRefresh: true,
        });

        let timer = setTimeout(() => {
            this.setState({
                mIsRefresh: false,
            });
            this._getDatas(new Date(), true);
            clearTimeout(timer);
        }, 1000)
    };

    /** 跳转仓体主页 */
    _onClickItem(item): void {
        this.props.navigation.navigate('CabinReport', {
            cabinName: item.item.cangName,            // 跳转的时候携带一个参数去下个页面
            cabinId: item.item.cangId,            // 跳转的时候携带一个参数去下个页面
            callback: (data) => { }
        })
    };
}

const styles = StyleSheet.create({
    item_layout_touch_bg: {
        marginHorizontal: 5,
        marginVertical: 10,
        borderRadius: 4,
        borderWidth: 0.5,
        borderColor: Color.lightMoreGray,
        backgroundColor: Color.windowWhiteLight,
    },

    item_layout: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        height: ITEM_HEIGHT * 1.5,
        paddingLeft: 10,
    },

    item_ing_line1: {
        width: 100,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },

    item_head: {
        height: 100,
        width: 100,
        borderRadius: 100,
    },

    text_tag: {
        fontSize: 14,
        // borderRadius: 4,
        // borderWidth: 1,
        // borderColor: Color.lightMoreGray,
    },
});
